package com.example.weather_app.diary;

import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.weather_app.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

public class AddDiaryActivity extends AppCompatActivity {
    private static final String TAG = "AddDiaryActivity";
    private EditText etTitle, etDate, etContent, etReminderTime;
    private Switch sbEnableReminder;
    private Button btnSave, btnCancel;
    private DiaryDao diaryDao;
    private String selectedDate;
    private String reminderTime;
    private SimpleDateFormat dateFormat, timeFormat;
    private Calendar reminderCalendar;
    private boolean isReminderSet = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate: Activity created");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_edit_diary);

        // 设置Toolbar
        androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("添加日记");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // 初始化组件
        etTitle = findViewById(R.id.etTitle);
        etDate = findViewById(R.id.etDate);
        etContent = findViewById(R.id.etContent);
        etReminderTime = findViewById(R.id.etReminderTime);
        sbEnableReminder = findViewById(R.id.sbEnableReminder);
        btnSave = findViewById(R.id.btnSave);
        btnCancel = findViewById(R.id.btnCancel);
        diaryDao = new DiaryDao(this);
        dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
        reminderCalendar = Calendar.getInstance();

        // 获取传入的日期
        if (getIntent() != null && getIntent().hasExtra("date")) {
            selectedDate = getIntent().getStringExtra("date");
            etDate.setText(selectedDate);
        } else {
            selectedDate = dateFormat.format(new Date());
            etDate.setText(selectedDate);
        }

        // 日期选择器
        etDate.setOnClickListener(v -> {
            Log.d(TAG, "etDate onClick: Date picker triggered");
            showDatePicker();
        });

        // 提醒时间选择器
        etReminderTime.setOnClickListener(v -> {
            Log.d(TAG, "etReminderTime onClick: Time picker triggered");
            showTimePicker();
        });

        // 启用提醒开关
        sbEnableReminder.setOnCheckedChangeListener((buttonView, isChecked) -> {
            Log.d(TAG, "sbEnableReminder onCheckedChanged: isChecked = " + isChecked);
            isReminderSet = isChecked;
            etReminderTime.setEnabled(isChecked);
        });

        // 保存按钮点击事件
        btnSave.setOnClickListener(v -> {
            Log.d(TAG, "btnSave onClick: Save diary triggered");
            saveDiary();
        });

        // 取消按钮点击事件
        btnCancel.setOnClickListener(v -> {
            Log.d(TAG, "btnCancel onClick: Cancel clicked");
            finish();
        });
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.root_layout), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    // 显示日期选择器
    private void showDatePicker() {
        Log.d(TAG, "showDatePicker: Date picker dialog shown");
        Calendar calendar = Calendar.getInstance();
        try {
            // 尝试解析当前日期
            Date currentDate = dateFormat.parse(selectedDate);
            calendar.setTime(currentDate);
        } catch (ParseException e) {
            Log.e(TAG, "Failed to parse selected date: " + selectedDate, e);
        }

        DatePickerDialog dialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    Log.d(TAG, "DatePickerDialog onDateSet: Selected date = " + year + "-" + (month + 1) + "-" + dayOfMonth);
                    selectedDate = year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth);
                    etDate.setText(selectedDate);
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        dialog.show();
    }

    // 显示时间选择器
    private void showTimePicker() {
        Log.d(TAG, "showTimePicker: Time picker dialog shown");
        Calendar calendar = Calendar.getInstance();

        // 解析用户选择的日期并设置到reminderCalendar
        try {
            Date selectedDateObj = dateFormat.parse(selectedDate);
            reminderCalendar.setTime(selectedDateObj);
        } catch (ParseException e) {
            Log.e(TAG, "Failed to parse selected date: " + selectedDate, e);
            // 如果解析失败，使用当前日期
            reminderCalendar = Calendar.getInstance();
        }

        TimePickerDialog dialog = new TimePickerDialog(
                this,
                (view, hourOfDay, minute) -> {
                    Log.d(TAG, "TimePickerDialog onTimeSet: Selected time = " + hourOfDay + ":" + minute);
                    // 设置时间到用户选择的日期上
                    reminderCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    reminderCalendar.set(Calendar.MINUTE, minute);
                    reminderCalendar.set(Calendar.SECOND, 0);

                    // 记录完整的提醒时间
                    reminderTime = timeFormat.format(reminderCalendar.getTime());
                    etReminderTime.setText(selectedDate + " " + reminderTime);

                    // 添加日志记录完整的提醒时间
                    long triggerTimeMillis = reminderCalendar.getTimeInMillis();
                    Log.d(TAG, "Reminder time set to: " + new Date(triggerTimeMillis) + " (" + triggerTimeMillis + "ms)");

                    // 检查设置的提醒时间是否在当前时间之前
                    long currentTimeMillis = System.currentTimeMillis();
                    if (triggerTimeMillis < currentTimeMillis) {
                        Log.w(TAG, "Warning: Reminder time is in the past!");
                        Toast.makeText(this, "提醒时间已过去，可能会立即触发", Toast.LENGTH_SHORT).show();
                    }
                },
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
        );
        dialog.show();
    }

    // 保存日记
    private void saveDiary() {
        Log.d(TAG, "saveDiary: Saving diary");
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();

        if (title.isEmpty() && content.isEmpty()) {
            Log.d(TAG, "saveDiary: Title and content are empty, showing error");
            etTitle.setError("请输入标题或内容");
            return;
        }

        Diary diary = new Diary();
        diary.setId(UUID.randomUUID().toString());
        diary.setTitle(title);
        diary.setContent(content);
        diary.setDate(selectedDate);

        if (isReminderSet && reminderTime != null) {
            String fullReminderTime = selectedDate + " " + reminderTime;
            Log.d(TAG, "saveDiary: Reminder is set, full reminder time: " + fullReminderTime);

            // 检查提醒时间是否有效
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                Date reminderDate = sdf.parse(fullReminderTime);
                long reminderMillis = reminderDate.getTime();
                long currentMillis = System.currentTimeMillis();

                if (reminderMillis < currentMillis) {
                    Log.w(TAG, "saveDiary: Warning - reminder time is in the past: " + fullReminderTime);
                    Toast.makeText(this, "提醒时间已过去，将不会设置提醒", Toast.LENGTH_SHORT).show();
                    diary.setReminderTime(null);
                } else {
                    diary.setReminderTime(fullReminderTime);
                    setReminder(diary.getId(), fullReminderTime);
                }
            } catch (ParseException e) {
                Log.e(TAG, "saveDiary: Invalid reminder time format: " + fullReminderTime, e);
                Toast.makeText(this, "提醒时间格式错误，将不会设置提醒", Toast.LENGTH_SHORT).show();
                diary.setReminderTime(null);
            }
        } else {
            Log.d(TAG, "saveDiary: Reminder is not set, setting reminder time to null");
            diary.setReminderTime(null);
        }

        long result = diaryDao.addDiary(diary);
        if (result > 0) {
            Log.d(TAG, "saveDiary: Diary saved successfully, finishing activity");
            Intent intent = new Intent();
            intent.putExtra("diaryId", diary.getId());
            setResult(RESULT_OK, intent);
            finish();
        } else {
            Log.d(TAG, "saveDiary: Failed to save diary");
            // 保存失败处理
        }
    }

    // 设置提醒（添加权限检查和异常处理）
    private void setReminder(String diaryId, String reminderTime) {
        Log.d(TAG, "setReminder: Setting reminder for diaryId = " + diaryId + ", reminderTime = " + reminderTime);

        // 记录当前时间和提醒时间的对比
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            long triggerTime = sdf.parse(reminderTime).getTime();
            long currentTime = System.currentTimeMillis();

            Log.d(TAG, "setReminder: Current time: " + new Date(currentTime));
            Log.d(TAG, "setReminder: Trigger time: " + new Date(triggerTime));
            Log.d(TAG, "setReminder: Time difference: " + (triggerTime - currentTime) + "ms");

            if (triggerTime < currentTime) {
                Log.e(TAG, "setReminder: ERROR - Trigger time is in the past!");
                Toast.makeText(this, "错误: 提醒时间已过去", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (ParseException e) {
            Log.e(TAG, "setReminder: Error parsing reminder time", e);
        }

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, ReminderReceiver.class);
        intent.setAction("com.example.weather_app.ACTION_DIARY_REMINDER");
        intent.putExtra("diaryId", diaryId);
        intent.putExtra("reminderTime", reminderTime); // 添加提醒时间作为额外参数

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this,
                diaryId.hashCode(),
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            long triggerTime = sdf.parse(reminderTime).getTime();

            // 关键修改：检查精确闹钟权限（Android 12+）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (!alarmManager.canScheduleExactAlarms()) {
                    Log.d(TAG, "setReminder: No exact alarm permission, showing toast and opening settings");
                    // 没有权限，提示用户并跳转到设置页面
                    Toast.makeText(this, "需要精确闹钟权限，请在设置中授予", Toast.LENGTH_SHORT).show();
                    Intent settingsIntent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
                    startActivity(settingsIntent);
                    return; // 不继续设置闹钟
                } else {
                    Log.d(TAG, "setReminder: Exact alarm permission granted");
                }
            }

            // 根据系统版本设置闹钟
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Log.d(TAG, "setReminder: Using setExactAndAllowWhileIdle for API " + Build.VERSION.SDK_INT);
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                Log.d(TAG, "setReminder: Using setExact for API " + Build.VERSION.SDK_INT);
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
            } else {
                Log.d(TAG, "setReminder: Using set for API " + Build.VERSION.SDK_INT);
                alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
            }

            Log.d(TAG, "setReminder: Alarm set successfully for time: " + new Date(triggerTime));

        } catch (ParseException e) {
            // 处理日期格式错误
            Log.e(TAG, "setReminder: 提醒时间格式错误: " + reminderTime, e);
            Toast.makeText(this, "提醒时间格式不正确，请使用 yyyy-MM-dd HH:mm:ss", Toast.LENGTH_LONG).show();
        } catch (SecurityException e) {
            // 处理权限被拒绝的情况
            Log.e(TAG, "setReminder: 设置精确闹钟被拒绝: " + e.getMessage(), e);
            Toast.makeText(this, "无法设置精确闹钟，请检查权限", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            // 处理其他异常
            Log.e(TAG, "setReminder: 设置提醒失败: " + e.getMessage(), e);
            e.printStackTrace();
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        Log.d(TAG, "onSupportNavigateUp: Navigating up");
        onBackPressed();
        return true;
    }
}